<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="箱码" prop="boxId">
        <el-input
          v-model="queryParams.boxId"
          placeholder="请输入箱码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货编码" prop="itemId">
        <el-input
          v-model="queryParams.itemId"
          placeholder="请输入存货编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购订单号" prop="poId">
        <el-input
          v-model="queryParams.poId"
          placeholder="请输入采购订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batch">
        <el-input
          v-model="queryParams.batch"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:boxCodes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:boxCodes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:boxCodes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:boxCodes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="boxCodesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="箱码" align="center" prop="boxId" />

      <el-table-column label="存货编码" align="center" prop="itemId" />
      <el-table-column label="存货名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="spec" width="120" />
      <el-table-column label="计量单位" align="center" prop="uom" width="80" />
      <el-table-column label="采购订单号" align="center" prop="poId" />
      <el-table-column label="批次号" align="center" prop="batch" />
      <el-table-column label="标箱数量" align="center" prop="boxNum" width="100" />
      <el-table-column label="检验状态" align="center" prop="inspectionStatus" />
      <el-table-column label="入库状态" align="center" prop="warehousingStatus" width="100">
      </el-table-column>
      <el-table-column label="生产日期" align="center" prop="productionDate">
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['purchase:boxCodes:list']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="handlePrint(scope.row)"
            v-hasPermi="['purchase:boxCodes:print']"
          >打印</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:boxCodes:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:boxCodes:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改箱码列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="箱码" prop="boxId">
          <el-input v-model="form.boxId" placeholder="请输入箱码" />
        </el-form-item>
        <el-form-item label="标箱数量" prop="boxNum">
          <el-input v-model="form.boxNum" placeholder="请输入标箱数量" />
        </el-form-item>
        <el-form-item label="存货编码" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入存货编码" />
        </el-form-item>
        <el-form-item label="采购订单号" prop="poId">
          <el-input v-model="form.poId" placeholder="请输入采购订单号" />
        </el-form-item>
        <el-form-item label="批次号" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="库位编号" prop="binId">
          <el-input v-model="form.binId" placeholder="请输入库位编号" />
        </el-form-item>
        <el-form-item label="生成时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择生成时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 箱码详情对话框 -->
    <el-dialog title="箱码详情" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-form ref="detailForm" :model="detailForm" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="箱码">
              <el-input v-model="detailForm.boxId" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存货编码">
              <el-input v-model="detailForm.itemId" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="存货名称">
              <el-input v-model="detailForm.itemName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号">
              <el-input v-model="detailForm.spec" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号">
              <el-input v-model="detailForm.batch" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位">
              <el-input v-model="detailForm.uom" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="采购订单号">
              <el-input v-model="detailForm.poId" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装箱数量">
              <el-input v-model="detailForm.boxNum" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="生产日期">
              <el-input :value="parseTime(detailForm.productionDate, '{y}-{m}-{d}')" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验状态">
              <el-input :value="getInspectionStatusText(detailForm.inspectionStatus)" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="入库状态">
              <el-input :value="getWarehousingStatusText(detailForm.warehousingStatus)" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-input :value="parseTime(detailForm.createdAt, '{y}-{m}-{d}')" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="创建人">
              <el-input v-model="detailForm.createdPerson" readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 打印内容区域（隐藏，只在打印时显示） -->
    <div id="printContent" style="display: none;">
      <div class="print-container" style="padding: 20px; font-family: 'Microsoft YaHei';">
        <div class="print-header" style="text-align: center; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px;">
          <h2 style="margin: 0; font-size: 24px;">箱码标签</h2>
        </div>

        <div class="print-body" style="display: flex; justify-content: space-between;">
          <!-- 左侧信息 -->
          <div class="left-info" style="flex: 1; padding-right: 20px;">
            <table style="width: 100%; border-collapse: collapse; font-size: 14px;">
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">箱码:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printBoxId"></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">存货编码:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printItemId"></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">存货名称:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printItemName"></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">规格型号:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printSpec"></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">批次号:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printBatch"></td>
              </tr>
            </table>
          </div>

          <!-- 右侧信息 -->
          <div class="right-info" style="flex: 1; padding-left: 20px;">
            <table style="width: 100%; border-collapse: collapse; font-size: 14px;">
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">计量单位:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printUom"></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">采购订单号:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printPoId"></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">装箱数量:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printBoxNum"></td>
              </tr>
              <tr>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd; font-weight: bold;">生产日期:</td>
                <td style="padding: 8px 0; border-bottom: 1px solid #ddd;" id="printProductionDate"></td>
              </tr>
            </table>
          </div>
        </div>

        <!-- 箱码条形码区域 -->
        <div class="barcode-section" style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 2px solid #000;">
          <svg id="barcode"></svg>
          <div style="font-size: 16px; font-weight: bold;" id="barcodeText"></div>
        </div>

        <div class="print-footer" style="text-align: center; margin-top: 30px; font-size: 12px; color: #666;">
          <p>打印时间: <span id="printTime"></span></p>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { listBoxCodes, getBoxCodes, delBoxCodes, addBoxCodes, updateBoxCodes } from "@/api/purchase/boxCodes"
import JsBarcode from 'jsbarcode';
export default {
  name: "BoxCodes",
  data() {
    return {
      detailOpen:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 箱码列表表格数据
      boxCodesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        boxId: null,
        boxNum: null,
        itemId: null,
        poId: null,
        batch: null,
        binId: null,
        inspectionStatus: null,
        warehousingStatus: null,
        createdAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      detailForm: {

      },
      resetDetailForm:{

      }
    }
  },
  created() {
    this.getList()
  },
  methods: {

    /** 详情按钮操作 */
    handleView(row) {
      this.detailForm= {};
      const id = row.id;
      getBoxCodes(id).then(response => {
        console.log("详情"+response);
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },

    /** 打印按钮操作 */
    handlePrint(row) {
      // 准备打印数据
      const printData = {
        boxId: row.boxId,
        itemId: row.itemId,
        itemName: row.itemName,
        spec: row.spec,
        batch: row.batch,
        uom: row.uom,
        poId: row.poId,
        boxNum: row.boxNum,
        productionDate: this.parseTime(row.productionDate, '{y}-{m}-{d}')
      };

      this.$modal.confirm('确定要打印该箱码标签吗？').then(() => {
        this.doPrint(printData);
      }).catch(() => {});
    },
    /** 执行打印 */
    doPrint(printData) {

      // 显示打印内容
      const printContent = document.getElementById('printContent');
      printContent.style.display = 'block';

      // 填充打印数据
      document.getElementById('printBoxId').textContent = printData.boxId;
      document.getElementById('printItemId').textContent = printData.itemId;
      document.getElementById('printItemName').textContent = printData.itemName;
      document.getElementById('printSpec').textContent = printData.spec;
      document.getElementById('printBatch').textContent = printData.batch;
      document.getElementById('printUom').textContent = printData.uom;
      document.getElementById('printPoId').textContent = printData.poId;
      document.getElementById('printBoxNum').textContent = printData.boxNum;
      document.getElementById('printProductionDate').textContent = printData.productionDate;
      document.getElementById('printTime').textContent = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
      document.getElementById('barcodeText').textContent = printData.boxId;

      /*/ 生成条形码*/
      this.generateBarcode(printData.boxId);
      // 执行打印
      setTimeout(() => {
        window.print();

        // 打印完成后隐藏打印内容
        setTimeout(() => {
          printContent.style.display = 'none';
        }, 500);
      }, 500);

    },
// 在 generateBarcode 方法中使用
    generateBarcode(barcodeText) {
      try {
        JsBarcode("#barcode", barcodeText, {
          format: "CODE128",
          lineColor: "#000",
          width: 2,
          height: 50,
          displayValue: true,
          fontOptions: "bold",
          font: "Arial",
          textMargin: 5,
          fontSize: 14
        });
      } catch (error) {
        console.error("生成条形码失败:", error);
        // 降级方案：显示文本
        const barcodeElement = document.getElementById('barcode');
        barcodeElement.innerHTML = `<div style="font-family: monospace; font-size: 16px; letter-spacing: 2px;">${barcodeText}</div>`;
      }
    },
    /** 查询箱码列表列表 */
    getList() {
      this.loading = true
      listBoxCodes(this.queryParams).then(response => {
        this.boxCodesList = response.rows
        this.total = response.total
        this.loading = false
        console.log(this.boxCodesList)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        boxId: null,
        boxNum: null,
        itemId: null,
        poId: null,
        batch: null,
        binId: null,
        inspectionStatus: null,
        warehousingStatus: null,
        createdAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加箱码列表"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getBoxCodes(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改箱码列表"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBoxCodes(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBoxCodes(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除箱码列表编号为"' + ids + '"的数据项？').then(function() {
        return delBoxCodes(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/boxCodes/export', {
        ...this.queryParams
      }, `boxCodes_${new Date().getTime()}.xlsx`)
    },
    // 原有的状态文本方法保持不变
    getInspectionStatusText(status) {
      const statusMap = {
        0: '未检验',
        1: '检验中',
        2: '检验通过',
        3: '检验不通过'
      };
      return statusMap[status] || '未知状态';
    },
    getWarehousingStatusText(status) {
      const statusMap = {
        0: '未入库',
        1: '已入库'
      };
      return statusMap[status] || '未知状态';
    }
  }
}
</script>
<style scoped>
/* 打印样式 */
@media print {
  /* 隐藏所有元素 */
  body * {
    visibility: hidden;
  }

  /* 只显示打印内容 */
  #printContent, #printContent * {
    visibility: visible;
  }

  /* 确保打印内容占据整个页面 */
  #printContent {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: white;
    z-index: 9999;
    margin: 0;
    padding: 20px;
    box-sizing: border-box;
  }

  /* 隐藏不需要打印的页面元素 */
  .el-header, .el-aside, .el-main > *:not(#printContent),
  .app-wrapper, .navbar, .tags-view, .app-main,
  .sidebar-container, .main-container {
    display: none !important;
  }

  /* 打印内容样式 */
  .print-container {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    border: 2px solid #000;
    padding: 20px;
    box-sizing: border-box;
  }

  /* 确保条形码可见 */
  #barcode {
    display: block !important;
    margin: 0 auto;
  }
}

/* 屏幕显示时隐藏打印内容 */
#printContent {
  display: none;
}
</style>
